package com.loginlib.login;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.loginlib.R;
import com.loginlib.di.component.DaggerLoginActivityComponent;
import com.loginlib.di.component.LoginActivityComponent;
import com.loginlib.di.module.LoginModule;
import com.loginlib.login.adapter.AccoutListAdapter;
import com.loginlib.panel.ILoginView;
import com.loginlib.presenters.UserCenterPresenter;
import com.loginlib.table.TableActivity;
import com.orhanobut.logger.Logger;
import com.wanhe.base.BaseActivity;
import com.wanhe.base.BuildConfig;
import com.wanhe.base.Const;
import com.wanhe.base.model.holder.DishHolder;
import com.wanhe.base.util.AppManager;
import com.wanhe.base.util.DeviceUtil;
import com.wanhe.base.util.FileDownLoadUtil;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.util.SystemUtil;
import com.wanhe.base.util.ViewUtil;
import com.wanhe.base.websocket.WebSocketTool;
import com.wanhe.base.websocket.callback.LoginCallBack;
import com.wanhe.base.websocket.model.response.BaseResponse;

import org.java_websocket.handshake.ServerHandshake;

import java.io.File;

import javax.inject.Inject;

/**
 * 登入界面
 */
public class LoginActivity extends BaseActivity implements ILoginView, LoginCallBack {

	EditText sclUsercenterLoginAccount;
	EditText sclUsercenterLoginPassword;
	TextView tvLoginButton;
	CheckBox cbRemenberPassword;
	@Inject
	UserCenterPresenter mPresenter;
	boolean savePassword;
	//    @Inject
	//    WebSocketTool webSocketTool;
	String account, password;
	Dialog versionDialog;

	@Override
	protected void initComponent(@Nullable Bundle savedInstanceState) {
		setContentView(R.layout.activity_loggin);
		sclUsercenterLoginAccount = (EditText) findViewById(R.id.scl_usercenter_login_account);
		sclUsercenterLoginPassword = (EditText) findViewById(R.id.scl_usercenter_login_password);
		tvLoginButton = (TextView) findViewById(R.id.tv_login_button);
		cbRemenberPassword = (CheckBox) findViewById(R.id.cb_remenber_password);
		savePassword = cbRemenberPassword.isChecked();
		System.gc();
		initInject();
		initEvent();
		if (!TextUtils.isEmpty(SPUtils.getAccount()) && savePassword) {
			sclUsercenterLoginAccount.setText(SPUtils.getAccount());
			sclUsercenterLoginPassword.setText(SPUtils.getPassword());
		}
		mPresenter.setLoadingView(this);
		mPresenter.initWebSocket();
		mPresenter.getVersion();
		mPresenter.setInitWebsocket(new WebSocketTool.WebSocketInitCallBack() {
			@Override
			public void onOpen(ServerHandshake serverHandshake) {
				Logger.d("onOpen");
			}

			@Override
			public void onClose(int code, String reason, boolean remote) {
				Logger.d("onClose");
			}
		});
	}

	private void initInject() {
		LoginActivityComponent component = DaggerLoginActivityComponent.builder().loginModule(new LoginModule(this)).build();
		component.inject(this);
	}

	protected void initEvent() {
		tvLoginButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				account = sclUsercenterLoginAccount.getText().toString().trim();
				password = sclUsercenterLoginPassword.getText().toString().trim();
				if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {
					Toast.makeText(LoginActivity.this, "账号和密码不能为空", Toast.LENGTH_SHORT).show();
					return;
				}

				if (BuildConfig.DEBUG) {
					Intent intent = new Intent(LoginActivity.this, TableActivity.class);
					startActivity(intent);
				} else {
					//					mPresenter.login(account, password);
					mPresenter.login2(account, password, DeviceUtil.getDeviceIDForServer(LoginActivity.this), LoginActivity.this);
				}
			}
		});
		//        sclUsercenterLoginAccount.setOnClickListener(new View.OnClickListener() {
		//            @Override
		//            public void onClick(View view) {
		//                // TODO: 2016/7/20 显示一个下拉菜单，显示之前登入的账号信息
		//                showAccountList();
		//            }
		//        });
	}


	/**
	 * 显示账户的下拉菜单
	 */
	private void showAccountList() {
		final PopupWindow window = new PopupWindow(this);
		window.setHeight(SystemUtil.getWindowWidthAndHeight(this)[1] / 5);
		window.setWidth(sclUsercenterLoginAccount.getWidth());
		window.setFocusable(true);
		window.setBackgroundDrawable(new ColorDrawable(0xb0000000));
		window.setOutsideTouchable(true);

		// TODO: 2016/7/27 设置一个listview
		ListView listView = new ListView(this);
		listView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		AccoutListAdapter accountAdapter = new AccoutListAdapter(this);
		accountAdapter.setListener(new AccoutListAdapter.OnAccountChosenListener() {
			@Override
			public void getAccount(String account, String password) {
				sclUsercenterLoginAccount.setText(account);
				sclUsercenterLoginPassword.setText(password);
				window.dismiss();
			}
		});
		//        mPresenter.setAccoutListAdapterWeakReference(accountAdapter);
		//        mPresenter.getHistoryAccountList();
		listView.setAdapter(accountAdapter);
		listView.setBackgroundColor(Color.WHITE);

		window.setContentView(listView);
		window.showAsDropDown(sclUsercenterLoginAccount, 0, 0);
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onLoading() {
		showDialog();
	}

	@Override
	public void onLoaded() {
		dismissDialog();
	}

	@Override
	public void onLoadFail(String msg) {
		ViewUtil.ShortToast(this, msg);
		dismissDialog();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			//            goback();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}


	@Override
	public void loginSuccess(String account, String password) {
		// TODO: 2016/7/19 进入到选择餐桌界面
		dismissDialog();
		SPUtils.setAccount(account);
		SPUtils.setPassword(password);
		//        if(savePassword){
		//
		//        }
		Intent intent = new Intent(this, TableActivity.class);
		startActivity(intent);
	}

	@Override
	public void checkLoginSuccess(String ip, String port) {

	}

	@Override
	public void updateVersion(String version) {
		String url = SPUtils.getResoureUrl() + "/GetPAD/" + version + ".apk";
		Log.i("initData", "update=" + url);
		versionDialog = ViewUtil.getCustomDialog(this, getDialogView(url, version));
		versionDialog.show();
	}

	private View getDialogView(final String url, final String version) {
		View view = LayoutInflater.from(this).inflate(R.layout.dialog_version, null);
		final Button sure = (Button) view.findViewById(R.id.btn_update_id_ok);
		final Button cancel = (Button) view.findViewById(R.id.btn_update_id_cancel);

		final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.update_progress);
		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (versionDialog != null) {
					versionDialog.dismiss();
				}
			}
		});
		sure.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				sure.setVisibility(View.GONE);
				cancel.setVisibility(View.GONE);
				FileDownLoadUtil.downloader(url, Const.fileBaseUrl + "/" + version + ".apk", new FileDownloadListener() {
					int progressMax = 0;

					@Override
					protected boolean isInvalid() {
						return LoginActivity.this.isFinishing();
					}

					@Override
					protected void pending(final BaseDownloadTask task, final int soFarBytes, final int totalBytes) {
						Log.d("MainActivity", "pending");
					}

					@Override
					protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
						super.connected(task, etag, isContinue, soFarBytes, totalBytes);
						Log.d("[pending] id[%d] %d/%d", task.getId() + "etag=" + etag + " soFarBytes=" + soFarBytes + " soFarBytes=" + totalBytes);
						Log.d("MainActivity", "connected");
					}

					@Override
					protected void progress(final BaseDownloadTask task, final int soFarBytes, final int totalBytes) {
						//                updateDisplay(String.format("[progress] id[%d] %d/%d", task.getDishGuid(), soFarBytes, totalBytes));
						Log.d("MainActivity", "progress=soFarBytes=" + soFarBytes);
						Log.d("MainActivity", "progress=totalBytes=" + totalBytes);
						if (progressMax == 0) {
							progressMax = totalBytes;
							progressBar.setMax(progressMax);
						}
						progressBar.setProgress(soFarBytes);
					}

					@Override
					protected void blockComplete(final BaseDownloadTask task) {
						Log.d("MainActivity", "blockComplete");
					}

					@Override
					protected void retry(BaseDownloadTask task, Throwable ex, int retryingTimes, int soFarBytes) {
						super.retry(task, ex, retryingTimes, soFarBytes);
						//                updateDisplay(String.format("[retry] id[%d] %s %d %d",
						//                        task.getDishGuid(), ex, retryingTimes, soFarBytes));
						Log.d("MainActivity", "retry");

					}

					@Override
					protected void completed(BaseDownloadTask task) {
						Log.d("MainActivity", "completed");
						ViewUtil.ShortToast(LoginActivity.this, "下载成功");
						if (versionDialog != null) {
							versionDialog.dismiss();
						}
						SPUtils.setVersion(version);
						//                        unstallApp();
						update(Const.fileBaseUrl, version + ".apk");
						AppManager.getAppManager().AppExit(LoginActivity.this);
					}

					@Override
					protected void paused(final BaseDownloadTask task, final int soFarBytes, final int totalBytes) {
						Log.d("MainActivity", "paused");
					}

					@Override
					protected void error(BaseDownloadTask task, Throwable e) {
						Log.d("MainActivity", "error" + e.getMessage());
						sure.setVisibility(View.GONE);
						cancel.setVisibility(View.GONE);
					}

					@Override
					protected void warn(BaseDownloadTask task) {
						Log.d("MainActivity", "warn");
					}
				});
			}
		});
		return view;
	}

	@Override
	public void onlogin(String body) {
		dismissDialog();
		Gson gson = new Gson();
		BaseResponse baseResponse = gson.fromJson(body, BaseResponse.class);
		if (baseResponse.getCode() == 0) {
			SPUtils.setAccount(account);
			SPUtils.setPassword(password);
			Intent intent = new Intent(this, TableActivity.class);
			startActivity(intent);
			finish();
		} else {
			ViewUtil.ShortToast(LoginActivity.this, baseResponse.getMessage());
		}
		//        mPresenter.heartBeat();
	}

	//卸载应用程序
	public void unstallApp() {
		Intent uninstall_intent = new Intent();
		uninstall_intent.setAction(Intent.ACTION_DELETE);
		uninstall_intent.setData(Uri.parse("package:" + this.getPackageName()));
		startActivity(uninstall_intent);
	}

	/**
	 * 安装程序
	 */
	void update(String path, String m_appNameStr) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(path, m_appNameStr)),
				"application/vnd.android.package-archive");
		this.startActivity(intent);
	}
}
